<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;

class CourierCompany extends Base
{
    use SoftDeletes;

    protected static function boot()
    {
        static::addGlobalScope('orderBySortIdDesc', function (Builder $builder) {
            $builder->orderBy('sort_id', 'ASC');
        });

        parent::boot(); // Base 的创建时间排序在后面, 优先 sort_id 排序
    }

    /**
     * 自定义操作日志 说明
     * @param $eventName
     * @return string
     */
    public function getDescriptionForEvent(string $eventName): string
    {
        if (!in_array($eventName, ['created', 'updated', 'deleted'])) {
            return $eventName;
        }

        switch ($eventName) {
            case 'created':
                return '创建快递公司:' . $this->name;
            case 'updated':
                $fieldMap = [
                    'name' => [
                        'title' => '快递公司名称',
                    ],
                    'sort_id' => [
                        'title' => '序列号',
                    ],
                ];
                $changes = [];
                foreach ($this->getChanges() as $field => $change) {
                    if (!isset($fieldMap[$field])) {
                        continue;
                    }

                    $changes[] = $fieldMap[$field]['title'] . '变更为' . (isset($fieldMap[$field]['casts']) ? $fieldMap[$field]['casts'][$change] : $change);
                }
                return '编辑快递公司:' . $this->getOriginal('name') . '; 变更内容:' . implode(',', $changes);
            case 'deleted':
                return '删除快递公司:' . $this->name;
            default:
                return $eventName;
        }
    }
}
